﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Resources;
using System.Text.RegularExpressions;

namespace CML.Intercamber.Web.Models
{
    public class TextTranslator
    {
        public string Code { get; set; }
        public Dictionary<string, string> Translations { get; set; }

        private static readonly Object textLocker = new Object();

        public static List<string> ListLanguages(string directory)
        {
            // Retrieve available languages
            List<string> languages = new List<string>();
            IEnumerable<string> files = Directory.EnumerateFiles(directory);
            foreach (string filePath in files)
            {
                Regex regex = new Regex("Intercamber.[a-zA-Z-]*.resx");
                // Save file name that matches with regex
                if (regex.IsMatch(filePath))
                {
                    // If the file is a language file
                    string fileName = Path.GetFileNameWithoutExtension(filePath);
                    string language = fileName.Replace("Intercamber.", string.Empty);
                    languages.Add(language);
                }
            }
            if (!languages.Contains("en"))
                languages.Add("en");
            return languages;
        }

        public static Dictionary<string, TextTranslator> LoadTextTranslators(string directory, string filter)
        {
            Dictionary<string, TextTranslator> res = new Dictionary<string, TextTranslator>();
            IEnumerable<string> files = Directory.EnumerateFiles(directory);
            Regex regex = new Regex("Intercamber.[a-zA-Z-]*.resx");
            foreach (string filePath in files)
            {
                string ext = Path.GetExtension(filePath);
                if (ext != ".resx")
                    continue;

                string language = "en";
                if (regex.IsMatch(filePath))
                    language = Path.GetFileNameWithoutExtension(filePath).Replace("Intercamber.", string.Empty);

                lock (textLocker)
                {
                    using (ResXResourceReader reader = new ResXResourceReader(filePath))
                    {
                        foreach (DictionaryEntry d in reader)
                        {
                            string key = d.Key.ToString();
                            string val = d.Value.ToString();
                            if (res.ContainsKey(key))
                            {
                                TextTranslator currentCode = res[key];
                                if (!currentCode.Translations.ContainsKey(language))
                                    currentCode.Translations.Add(language, val);
                            }
                            else
                            {
                                res.Add(key, new TextTranslator
                                {
                                    Code = key,
                                    Translations = new Dictionary<string, string> {{language, val}}
                                });
                            }
                        }
                    }
                }
            }

            // filtre 
            if (!string.IsNullOrEmpty(filter))
            {
                List<string> keysToRemove = new List<string>();
                string filterUpper = filter.ToUpper().Trim();
                foreach (string k in res.Keys)
                {
                    if (!k.ToUpper().Contains(filterUpper) && !res[k].Translations.Any(x => x.Value.ToUpper().Contains(filterUpper)))
                        keysToRemove.Add(k);
                }
                foreach (var k in keysToRemove)
                    res.Remove(k);
            }


            return res;
        }

        public static void UpdateText(string language, string code, string updatedValue, string resourcesDirectory)
        {
            Hashtable oHt = new Hashtable();

            lock (textLocker)
            {
                string sPath = resourcesDirectory + "Intercamber" + (language == "en" ? "" : "." + language) + ".resx";
                using (ResXResourceReader oReader = new ResXResourceReader(sPath))
                {
                    IDictionaryEnumerator oResource = oReader.GetEnumerator();
                    while (oResource.MoveNext())
                        oHt.Add(oResource.Key, oResource.Value);
                }

                oHt[code] = updatedValue;

                using (ResXResourceWriter oWriter = new ResXResourceWriter(sPath))
                {

                    foreach (string key in oHt.Keys)
                        oWriter.AddResource(key, oHt[key].ToString());
                    oWriter.Generate();
                }
            }
        }

    }
}